// utils/webSocketManager.js
class WebSocketManager {
    constructor() {
      this.socket = null;
      this.callbacks = {};
    }
  
    connect(url) {
      if (!this.socket) {
        console.log("No websocket fount, start connect to {}...", url)
        let token = wx.getStorageSync("token");
        // header.Authorization = token;
        let header = {}
        header['authorization'] = "Bearer " + token;
        this.socket = wx.connectSocket({ 
            url: url,
            header : header,
        });
        this.socket.onOpen(() => {
          console.log('WebSocket connection opened');
          this.pingInterval = setInterval(() => {
            console.log('Send ping message...');
            this.socket.send({ 
              data: 'ping' // You can send a specific ping message if your server expects one
            });
          }, 30000); // 30 seconds
        });
  
        this.socket.onClose(() => {
          console.log('WebSocket connection closed');
          this.socket = null;
        });
  
        this.socket.onMessage((message) => {
          const data = JSON.parse(message.data);
          
          this.notify(data);
        });
  
        this.socket.onError((error) => {
          console.error('WebSocket error:', error);
        });
      }
      else{
        console.log('WebSocket already exist.');
      }
    }
  
    notify(data) {
      const type = data.messageType;
      const payload = data.message;
      if (this.callbacks[type]) {
        this.callbacks[type].forEach(callback => callback(payload));
      }
    }
  
    registerCallback(type, callback) {
      if (!this.callbacks[type]) {
        this.callbacks[type] = [];
      }
      this.callbacks[type].push(callback);
    }
  
    unregisterCallback(type, callback) {
      if (this.callbacks[type]) {
        this.callbacks[type] = this.callbacks[type].filter(cb => cb !== callback);
      }
    }
  
    sendMessage(message) {
      if (this.socket) {
        console.log(`Sending message to ws: ${JSON.stringify(message)}`)
        this.socket.send({
          data: JSON.stringify(message)
        });
      }
      console.log(`Sending message to ws: ${JSON.stringify(message)}`)
    }
  
    close() {
      if (this.socket) {
        this.socket.close();
      }
    }
  }
  
  const webSocketManager = new WebSocketManager();
  export default webSocketManager;
  